package com.eltonkent.dashboard.util.logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;

import android.os.Environment;
import android.util.Log;

import com.eltonkent.dashboard.util.SDCardInfo;

class LoggerStrategyFS implements ILoggerStrategy {
	protected FileWriter writer;
	private File logDirectory;
	private File currentLogFile;
	private final String[] LEVELS = { "Verbose", "Debug", "Info", "Warn",
			"Error" };
	private boolean noSdCard;

	LoggerStrategyFS(String directory, String fileName) {
		logDirectory = new File(Environment.getExternalStorageDirectory(),
				directory);
		if (SDCardInfo.isMounted()) {
			try {
				String fname = fileName;// "log_" + new Date().getTime() +
				// ".txt";
				if (logDirectory.isFile()) {
					logDirectory.delete();
				}
				if (!logDirectory.exists()) {
					logDirectory.mkdir();
				}

				currentLogFile = new File(logDirectory, fname);
				writer = new FileWriter(currentLogFile, true);
			} catch (IOException e) {
				e.printStackTrace();
				Log.e("Logger", e.getMessage());
			}
		} else {
			noSdCard = true;

		}
	}

	public void d(String tag, String message) {
		write(Log.DEBUG, tag, message);
	}

	public void e(String tag, String message) {
		write(Log.ERROR, tag, message);
	}

	protected String formatDate(Date date) {
		return MessageFormat.format("{0,date} {0,time}", date);
	}

	public void i(String tag, String message) {
		write(Log.INFO, tag, message);
	}

	protected String levelToString(int level) {
		return LEVELS[level - 2];
	}

	@Override
	public void shutdown() {
		Log.d("Logger", "Shutting down logger");
		if (!noSdCard) {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// remove all files but the current file
			File[] allfiles = logDirectory.listFiles();
			for (int i = 0; i < allfiles.length; i++) {
				if (!currentLogFile.equals(allfiles[i])) {
					Log.d("Logger", "Removing old log file:" + allfiles[i]);
					allfiles[i].delete();
				}
			}
		}
	}

	public void v(String tag, String message) {
		write(Log.VERBOSE, tag, message);
	}

	public void w(String tag, String message) {
		write(Log.WARN, tag, message);
	}

	public void write(int level, String tag, String message) {
		writeImpl(level, tag, message);
	}

	private void writeImpl(int level, String tag, String message) {
		if (writer != null) {
			try {
				writer.write("[" + formatDate(new Date()) + "] "
						+ levelToString(level) + " [" + tag + "] " + message
						+ "\r\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}/* else { */
		Log.println(level, tag, message);
		// }
	}
}
